<template>
  <Table
    :columns="columns"
    :data-source="schools"
    :loading="loading"
    :pagination="pagination"
    :scroll="{ x: 'max-content', y: 'calc(100vh - 550px)' }"
    row-key="id"
    @change="handleTableChange"
    class="centered-table"
  >
  </Table>
</template>

<script setup lang="ts">
import { ref, computed, h } from "vue";
import { useRouter } from "vue-router";
import { Table, Button, Popconfirm, message, Tag } from "ant-design-vue";
import type { School } from "../types/school";
import Api from "@/api/school.js";
import { useSchoolStore } from "../stores/schoolStore";

const props = defineProps<{
  schools: School[];
  loading: boolean;
  pagination?: {
    current: number;
    pageSize: number;
    total: number;
  };
}>();

const emit = defineEmits(["refresh", "pageChange"]);

const router = useRouter();
const schoolStore = useSchoolStore();

const handleEdit = (record: School) => {
  schoolStore.setCurrentSchool(record);
  router.push(`/schools/edit/${record.id}`);
};

const handleDelete = async (record: School) => {
  try {
    if (!record.id || !record.dsCode) {
      message.error("缺少学校ID或地市编码");
      return;
    }

    await Api.del({ id: record.id, dsCode: record.dsCode });
    message.success("删除成功");
    emit("refresh");
  } catch (error) {
    if (error instanceof Error) {
      message.error(error.message);
    } else {
      message.error("删除失败");
    }
  }
};

const handleTableChange = (pagination: any) => {
  emit("pageChange", {
    current: pagination.current,
    pageSize: pagination.pageSize,
  });
};

// 表格列定义
const columns = ref<any>([
  {
    title: "学校名称",
    dataIndex: "xxmc",
    key: "xxmc",
    width: 180,
    align: "center",
    customRender: ({ text, record }: { text: string; record: School }) => {
      const tags = [];

      if (record.isComplete === false) {
        tags.push(
          h(
            Tag,
            { color: "warning", style: { marginLeft: "8px" } },
            () => "信息不完整"
          )
        );
      }

      if (record.isDraft) {
        tags.push(
          h(Tag, { color: "blue", style: { marginLeft: "8px" } }, () => "草稿")
        );
      }

      if (tags.length > 0) {
        return h("div", { class: "center-align" }, [text, ...tags]);
      }

      return h("span", {}, text);
    },
  },
  {
    title: "地市",
    dataIndex: "ds",
    key: "ds",
    width: 100,
    align: "center",
  },
  {
    title: "区县",
    dataIndex: "qx",
    key: "qx",
    width: 100,
    align: "center",
  },
  {
    title: "街道",
    dataIndex: "jd",
    key: "jd",
    width: 120,
    align: "center",
  },
  {
    title: "社区",
    dataIndex: "sq",
    key: "sq",
    width: 120,
    align: "center",
  },
  {
    title: "学校类型",
    dataIndex: "xxlx",
    key: "xxlx",
    width: 100,
    align: "center",
  },
  {
    title: "联系电话",
    dataIndex: "lxdh",
    key: "lxdh",
    width: 150,
    align: "center",
  },
  {
    title: "学生人数",
    dataIndex: "xsrsgm",
    key: "xsrsgm",
    width: 100,
    align: "center",
  },
  {
    title: "上学高峰时段",
    dataIndex: "sxgfsd",
    key: "sxgfsd",
    width: 150,
    align: "center",
  },
  {
    title: "下学高峰时段",
    dataIndex: "xxgfsd",
    key: "xxgfsd",
    width: 150,
    align: "center",
  },
  {
    title: "接送管控类别",
    dataIndex: "jsgklb",
    key: "jsgklb",
    width: 150,
    align: "center",
  },
  {
    title: "责任中队",
    dataIndex: "zrzd",
    key: "zrzd",
    width: 120,
    align: "center",
  },
  {
    title: "中队负责人",
    dataIndex: "zdfzr",
    key: "zdfzr",
    width: 120,
    align: "center",
  },
  {
    title: "负责人联系电话",
    dataIndex: "fzrlxdh",
    key: "fzrlxdh",
    width: 150,
    align: "center",
  },
  {
    title: "是否上传秩序管控方案",
    dataIndex: "sfsczxgkfa",
    key: "sfsczxgkfa",
    width: 180,
    align: "center",
    customRender: ({ text }: { text: number }) => {
      return h("span", {}, text == 1 ? "是" : "否");
    },
  },
  {
    title: "操作",
    key: "action",
    fixed: "right",
    width: 120,
    align: "center",
    customRender: ({ record }: { record: School }) => {
      return h("div", { class: "operation-buttons" }, [
        h(
          Button,
          {
            type: "link",
            size: "small",
            onClick: () => handleEdit(record),
          },
          () => "编辑"
        ),
        h(
          Popconfirm,
          {
            title: "确定删除该学校吗?",
            onConfirm: () => handleDelete(record),
            "ok-text": "确定",
            "cancel-text": "取消",
          },
          {
            default: () =>
              h(
                Button,
                {
                  type: "link",
                  danger: true,
                  size: "small",
                },
                () => "删除"
              ),
          }
        ),
      ]);
    },
  },
]);
</script>

<style scoped>
.centered-table :deep(.ant-table-thead > tr > th) {
  text-align: center;
}

.centered-table :deep(.ant-table-tbody > tr > td) {
  text-align: center;
}

.center-align {
  display: flex;
  align-items: center;
  justify-content: center;
}

.operation-buttons {
  display: flex;
  justify-content: center;
  gap: 8px;
}
</style>
